﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Xml;
namespace Client
{
    public partial class QuanLy : Form
    {
        public QuanLy()
        {
            InitializeComponent();
        }
        #region Bien

        IPEndPoint ipe;
        StreamReader recv;       // Bo doc du lieu  
        StreamWriter send;       // Bo gui du lieu
        TcpClient client;
        CConfig config;       // file config
        string user;         // Tai khoan nguoi dung
        DangNhap frm = new DangNhap();  // Form Dang Nhap
        DangKy dkfrm = new DangKy();    // Form Dang Ky
        ThongKe tk = new ThongKe();     //Form Thong Ke
        bool isDangNhap = false;
        public List<CProduct> dssanpham = new List<CProduct>();     //Danh sach san phamn chua san pham nhan duoc tu server
        int flag;       //Bien the hien khoi tao ket noi co thanh cong hay khong
        int disconnet = 0;
        #endregion

        #region Ham Xu Ly

        #region Ham khoi tao ket noi
        public int KhoiTaoKetNoi()
        {
        laplai:
            try
            {
                //tao doi tuong config chua thong tin lay len tu file config
                config = new CConfig();
                //tao ipendpoint voi tham so dau vao la ip va port duoc chua trong config
                ipe = new IPEndPoint(IPAddress.Parse(config.Ip), config.Port);
                //Khoi tao doi tuong client
                client = new TcpClient();
                //Thuc hien ket noi den Server
                client.Connect(ipe);

            }
            catch
            {

            }
            if (client.Connected == true)
            {
                // neu ket noi thanh cong thi tao ra 2 doi tuong gui va nhan du lieu
                recv = new StreamReader(client.GetStream());
                send = new StreamWriter(client.GetStream());
                return 1;// tra ve gia tri 1 bao ket noi thanh cong
            }
            else // ket noi khong thanh cong
            {
                try
                {
                    //ket noi lai voi dia chi ip lay duoc tu hostnameserver chua trong config
                    ipe = new IPEndPoint(Dns.GetHostAddresses(config.Hostserver)[0], config.Port);
                    //thuc hien ket noi
                    client.Connect(ipe);
                    //ket noi thanh cong => tao 2 bo gui nhan du lieu
                    recv = new StreamReader(client.GetStream());
                    send = new StreamWriter(client.GetStream());
                    return 1;// tra ve gia tri 1 bao ket noi thanh cong
                }
                catch
                {
                    //ket noi that bai hoan toan
                    MessageBox.Show("Kết nối đến Server thất bại.", "Kết nối", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    // hien form Thiet Lap de nguoi dung thiet lap lai ip port va hostnameserver
                    ThietLap setting = new ThietLap();
                    setting.flag = 0;
                    setting.ShowDialog();
                    if (setting.flag == 1)
                    {
                        //thuc hien ket noi lai lan nua
                        goto laplai;
                    }
                    //tra ve gia tri 0 thong bao ket noi that bai => thoat chuong trinh
                    return 0;
                }
            }
        }
        #endregion


        #region Ham xu ly dong ket noi
        bool isGuiDoanhThu = false;
        //gui doanh thu truoc khi dong 
        private void GuiDoanhThu()
        {
            try
            {
                //Doc file log xml
                XmlDocument log = new XmlDocument();
                log.Load("log.xml");
                XmlElement root = log.DocumentElement;
                //Gui doanh thu len server
                send.AutoFlush = true;

                foreach (XmlElement nodeSanPham in root.SelectNodes("Sanpham"))
                {
                    string id = nodeSanPham.GetAttribute("id");
                    string soluong = nodeSanPham.GetAttribute("soluong");
                    string thanhtien = nodeSanPham.GetAttribute("thanhtien");
                    string ngayban = nodeSanPham.GetAttribute("ngayban");
                    DateTime time = ConvertNgay(ngayban);
                    string mess = "sale|" + user + "|" + id + "|" + soluong + "|" + thanhtien + "|" + time.ToShortDateString();
                    mess = CCryptography.MaHoa(mess);
                    send.WriteLine(mess);
                    isGuiDoanhThu = true;
                }
                send.Flush();
                root.RemoveAll();
                log.Save("log.xml");

            }
            catch
            {
            }

        }
        private void Disconnect()
        {
            //Dong ket noi


            send.Flush();
            recv.Close();
            send.Close();
            client.Close();
        }
        #endregion

        #region Ham gui
        /// <summary>
        /// Send du lieu
        /// </summary>
        /// <param name="mess"></param>
        private void Send(string mess)
        {
            mess = CCryptography.MaHoa(mess);
            send.WriteLine(mess);
            send.Flush();
        }
        #endregion

        #region Ham nhan goi tin va cac ham xu ly goi tin
        /// <summary>
        /// Lắng nghe để nhậ dữ liệu từ server gửi wa
        /// </summary>
        private void NhanDuLieu()
        {
            try
            {
                //Luon luon lang nghe
                while (true)
                {
                    //Nhan goi tin tu server
                    string mess = recv.ReadLine();
                    //Giãi mã gói tin
                    mess = CCryptography.GiaiMa(mess);
                    //Phan tich goi tin thong qua ham XuLyThongTin
                    string[] inf = XuLyThongTin(mess);
                    //Dua vao header de thuc hien cac chuc nang can thiet
                    switch (inf[0].Trim())
                    {

                        case "quit":
                            Disconnect();
                            MessageBox.Show("Disconnect Server.....");
                            disconnet = 1;
                            Application.Exit();
                            return;
                        case "update": // cap nhat gia cho 1 san pham
                            Update(inf);
                            break;
                        case "report":// nhan thong ke
                            ThongKe(inf);
                            break;
                        case "login"://nhan ket qua login
                            login(inf);
                            break;
                        case "register":
                            register(inf);
                            break;
                        case "init":
                            init(inf);
                            break;
                        default:
                            break;

                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }


        #region Xu ly goi tin
        private string[] XuLyThongTin(string mess)
        {
            string[] result;
            //Split chuoi nhan duoc
            result = mess.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            return result;
        }
        #endregion

        #region Xu ly ngay thang
        private DateTime ConvertNgay(string strdate)
        {
            string[] arr = strdate.Split(new char[] { '/', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            string str = arr[0] + "/" + arr[1] + "/" + arr[2];

            DateTime date = new DateTime();
            if (!DateTime.TryParse(str, out date))
            {
                str = arr[1] + "/" + arr[0] + "/" + arr[2];
                DateTime.TryParse(str, out date);
            }
            return date;
        }
        #endregion

        #region Doc danh sach san pham
        XmlDocument LoadTextXML(string strXML)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.PreserveWhitespace = false;
                xmlDoc.XmlResolver = null;
                xmlDoc.LoadXml(strXML);
                return xmlDoc;
            }
            catch (Exception c)
            {
                throw new Exception(c.Message);
            }
        }
        public List<CProduct> LayDanhSachSanPham(string ds)
        {
            List<CProduct> listproduct = new List<CProduct>();
            XmlDocument xmlDoc = LoadTextXML(ds);
            XmlNodeList fullList = xmlDoc.SelectNodes("//sanpham");

            if (fullList.Count != 0)
            {
                foreach (XmlNode node in fullList)
                {
                    try
                    {
                        XmlNodeList childnode = node.ChildNodes;
                        CProduct product = new CProduct(childnode);
                        listproduct.Add(product);
                    }
                    catch (Exception c)
                    {
                        throw new Exception("Đinh dang CSDL không dúng");
                    }
                }
            }
            return listproduct;
        }
        #endregion

        #region init
        private void init(string[] inf)
        {
            dssanpham = LayDanhSachSanPham(inf[1]);
            LoadDanhSachCapNhat();
            MessageBox.Show("Cập nhật thành công");
        }
        private void LoadDanhSach()
        {
            int dem = 0;
            foreach (CProduct i in dssanpham)
            {

                SanPhamControl c = new SanPhamControl();
                c.lbgia.Text = i.Giatien.ToString();
                c.lbTen.Text = i.Ten.ToString();
                Point newP = new Point();
                newP.X = 10 + c.Width * (dem % 5);
                newP.Y = c.Height * (dem / 5);
                c.Location = newP;
                c.sanpham = i;
                this.Invoke((Action)(() => pnCuaHang.Controls.Add(c)));
                pnCuaHang.Refresh();
                dem++;

            }
        }
        #endregion

        #region login
        private void login(string[] c)
        {
            if (c[0] == "login")
            {
                int id = int.Parse(c[1]);
                if (id != 0)
                {
                    MessageBox.Show("Đăng Nhập Thành Công.");
                    dssanpham = LayDanhSachSanPham(c[2]);
                    frm.Invoke((Action)(() => frm.Close()));
                    isDangNhap = true;
                }
                else
                {
                    MessageBox.Show("Thông tin đăng nhập không hợp lệ.", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        void frm_LoginEvent(Form frm, string username, string pass)
        {
            string ttdangnhap = "login|" + username + "|" + pass;
            Send(ttdangnhap);
            config.GhiFileConfig(username, pass);
            user = username;
            //throw new NotImplementedException();          
        }


        #endregion

        #region update
        private void Update(string[] inf)
        {
            CProduct sp = new CProduct();
            sp.Ma = int.Parse(inf[1]);
            sp.Ten = inf[2];
            sp.Giatien = double.Parse(inf[3]);
            sp.Ngaydang = ConvertNgay(inf[5]);
            sp.Mota = inf[4];
            int stt = 0;
            int flag = 0;
            foreach (CProduct i in dssanpham)
            {
                if (i.Ma == sp.Ma)
                {
                    flag = 1;
                    dssanpham[stt] = sp;
                    break;
                }
                stt++;
            }
            if (flag == 0)
                dssanpham.Add(sp);
            LoadDanhSachCapNhat();
        }
        private void LoadDanhSachCapNhat()
        {
            this.Invoke((Action)(() => pnCuaHang.Controls.Clear()));
            int dem = 0;
            foreach (CProduct i in dssanpham)
            {

                SanPhamControl c = new SanPhamControl();
                c.lbgia.Text = i.Giatien.ToString();
                c.lbTen.Text = i.Ten.ToString();
                Point newP = new Point();
                newP.X = 10 + c.Width * (dem % 5);
                newP.Y = c.Height * (dem / 5);
                c.Location = newP;
                c.sanpham = i;

                this.Invoke((Action)(() => pnCuaHang.Controls.Add(c)));

                dem++;

            }
        }
        #endregion

        #region report

        private void ThongKe(string[] inf)
        {
            //Goi Form ThongKe va truyen tham so
            tk.Invoke((Action)(() => tk.tvReport.Nodes.Clear()));
            tk.Invoke((Action)(() => tk.tvReport.Nodes.Add(inf[1])));
            tk.Invoke((Action)(() => tk.tvReport.Nodes[0].Nodes.Add(inf[2])));
            tk.Invoke((Action)(() => tk.tvReport.Nodes[0].Nodes.Add(inf[3])));
            tk.Invoke((Action)(() => tk.tvReport.Nodes[0].Nodes.Add(inf[4])));
            tk.Invoke((Action)(() => tk.tvReport.Nodes[0].Nodes.Add(inf[5])));

            for (int i = 6; i < inf.Length; i++)
            {
                tk.Invoke((Action)(() => tk.tvReport.Nodes[0].Nodes[3].Nodes.Add(inf[i])));


            }

        }

        void tk_ReportEvent(DateTime ngaythongke)
        {
            string mess = "report|" + user + "|" + ConvertNgay(ngaythongke.ToShortDateString()).ToShortDateString();
            Send(mess);
            //throw new NotImplementedException();
        }
        #endregion

        #region register

        void register(string[] inf)
        {
            int flag = int.Parse(inf[1]);
            if (flag != 0)
            {
                MessageBox.Show("Đăng Ký Thành Công.");
                dkfrm.Invoke((Action)(() => dkfrm.Close()));

            }
            else
            {
                MessageBox.Show("Đăng ký thất bại.", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        void frm_RegisterEvent(Form frm)
        {

            dkfrm.RegisterEvent += new DangKy.RegisterHanler(dkfrm_RegisterEvent);
            dkfrm.ShowDialog();

            //throw new NotImplementedException();
        }

        void dkfrm_RegisterEvent(string tk, string pass, string truso, string diachi, string dienthoai, string email)
        {
            string mess = "register|" + tk + "|" + pass + "|" + truso + "|" + diachi + "|" + dienthoai + "|" + email;
            Send(mess);
            //throw new NotImplementedException();
        }

        #endregion

        #endregion


        #region Cac su kien cua Button

        private void btnThongKe_Click(object sender, EventArgs e)
        {
            GuiDoanhThu();
            isGuiDoanhThu = false;
            tk.ReportEvent += new Client.ThongKe.ReportHanler(tk_ReportEvent);

            tk.ShowDialog();
        }
        private void btnThietLap_Click(object sender, EventArgs e)
        {
            //Goi Form Thiet Lap 
            ThietLap tl = new ThietLap();
            tl.ShowDialog();

        }


        private void btnclose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //Thong bao cho nguoi dung

            this.Close();

        }
        private void btnUpload_Click(object sender, EventArgs e)
        {
            GuiDoanhThu();
            if (isGuiDoanhThu)
            {
                MessageBox.Show("Gửi doanh thu thành công");
                isGuiDoanhThu = false;
            }
            else
            {
                MessageBox.Show("Chưa bán sản phẩm nào. Không có thông tin để gửi đi");                
            }
        }

        private void btnDownLoad_Click(object sender, EventArgs e)
        {
            Send("init");
        }

        #endregion

        #region Cac Event cua Form
        /// <summary>
        /// Sự kiện load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QuanLy_Load(object sender, EventArgs e)
        {
            //Khởi tạo kết  nối
            flag = KhoiTaoKetNoi();
            if (flag == 0)
            {
                Application.Exit();
            }
            else
            {
                //khởi tạo Thread để lắng nghe kết nối
                Thread listen = new Thread(NhanDuLieu);
                //Bắt đầu Thread
                listen.Start();

                frm.LoginEvent += new DangNhap.LoginHandler(frm_LoginEvent);
                frm.RegisterEvent += new DangNhap.RegisterHandler(frm_RegisterEvent);
                frm.DongFormEvent += new DangNhap.DongFormHandler(frm_DongFormEvent);
                frm.ShowDialog();

                //Hiện danh sách sản phẩm
                LoadDanhSach();
            }
        }
        /// <summary>
        /// Dong from login
        /// </summary>
        void frm_DongFormEvent()
        {
            this.Close();
        }
        /// <summary>
        /// Form Closing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QuanLy_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (flag != 0)
            {
                //Gui doanh thu cho server
                if (disconnet != 1)
                {
                    //Kiem tra da dang nhap hay chua
                    if (isDangNhap != false)
                    {
                        DialogResult result = MessageBox.Show("Trước khi thoát hãy kiểm tra dữ liệu gửi cho Server . Bạn muốn thoát ??", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                        if (result == DialogResult.OK)
                        {
                            GuiDoanhThu();
                            Send("quit");
                        }
                        else
                        {
                            e.Cancel = true;
                        }
                    }
                    else
                    {
                        Send("quit");
                    }
                }
                else
                {
                    Application.Exit();
                }
            }
        }
        #endregion
        #endregion
    }
}
